package com.ly.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.common.core.constant.BaseConstant;
import com.ly.common.core.enums.MenuIndexEnum;
import com.ly.common.core.exception.ServiceException;
import com.ly.common.core.utils.BaseUtils;
import com.ly.common.core.utils.RedisUtils;
import com.ly.system.mapper.SysPermissionMapper;
import com.ly.system.mapper.SysRoleIndexMapper;
import com.ly.system.mapper.SysUserRoleMapper;
import com.ly.system.service.ISysRoleIndexService;
import com.ly.system.system.bean.entity.SysPermission;
import com.ly.system.system.bean.entity.SysRoleIndex;
import com.ly.system.system.bean.entity.SysUserRole;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色首页配置
 *
 * @author jeecg
 * @Date: 2022-03-25
 */
@Service("sysRoleIndexServiceImpl")
@Slf4j
@RequiredArgsConstructor
public class SysRoleIndexServiceImpl extends ServiceImpl<SysRoleIndexMapper, SysRoleIndex> implements ISysRoleIndexService {

    private final RedisUtils redisUtil;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysPermissionMapper sysPermissionMapper;

    @Override
    public R getId(String id) {
        SysRoleIndex entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(SysRoleIndex entity) {
        List<SysRoleIndex> list = this.list(
                new LambdaQueryWrapper<SysRoleIndex>()
                        .eq(StrUtil.isNotEmpty(entity.getComponent()), SysRoleIndex::getComponent, entity.getComponent())
                        .like(StrUtil.isNotBlank(entity.getRoleId()), SysRoleIndex::getRoleId, entity.getRoleId())
                        .orderByDesc(SysRoleIndex::getCreateTime)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(SysRoleIndex entity, Page<SysRoleIndex> page) {
        IPage<SysRoleIndex> pageList = this.page(
                page,
                new LambdaQueryWrapper<SysRoleIndex>()
                        .eq(StrUtil.isNotEmpty(entity.getComponent()), SysRoleIndex::getComponent, entity.getComponent())
                        .like(StrUtil.isNotBlank(entity.getRoleId()), SysRoleIndex::getRoleId, entity.getRoleId())
                        .orderByDesc(SysRoleIndex::getCreateTime)
        );
        return R.ok(pageList);
    }
    
    @Override
    public R add(SysRoleIndex entity) {
        this.getSysRoleIndexByEntity(entity);
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "保存成功") : R.fail("保存失败");
    }

    @Override
    public R edit(SysRoleIndex entity) {
        String roleCode = entity.getRoleId();
        if ("admin".equals(roleCode)) {
            return R.fail("超级管理员角色首页不允许修改");
        }
        // 删除存在的
        this.remove(
                new LambdaQueryWrapper<SysRoleIndex>()
                        .eq(SysRoleIndex::getRoleId, roleCode)
        );
        this.getSysRoleIndexByEntity(entity);
        boolean flag = this.saveOrUpdate(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<SysRoleIndex> dto) {
        List<SysRoleIndex> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    public SysRoleIndex queryDefaultIndex(String roleCode) {
        String indexUrl = this.getIndexUrlByUserName(BaseUtils.getId());
        SysRoleIndex entity = new SysRoleIndex();
        entity.setUrl(indexUrl);
        this.getSysRoleIndexByEntity(entity);
        return entity;
    }

    /**
     * 根据页面url，填充首页配置信息
     *
     * @param entity
     * @return
     */
    private void getSysRoleIndexByEntity(SysRoleIndex entity) {
        String url = entity.getUrl();
        if (url == null) {
            throw new ServiceException("菜单路径不能为空，请先检查！");
        }
        SysPermission indexMenu = sysPermissionMapper.selectOne(
                new LambdaQueryWrapper<SysPermission>()
                        .eq(SysPermission::getUrl, url)
        );
        if (indexMenu == null) {
            throw new ServiceException("菜单路径有错误，请先检查！");
        }
        // entity.setUrl(url);
        entity.setComponent(indexMenu.getComponent());
        entity.setRoute(indexMenu.getRoute());
        entity.setStatus(BaseConstant.STATUS_1);
    }

    @Override
    public SysRoleIndex updateDefaultIndex(SysRoleIndex entity) {
        // 删除存在的
        this.remove(
                new LambdaQueryWrapper<SysRoleIndex>()
                        .eq(SysRoleIndex::getRoleId, MenuIndexEnum.GLOBAL.getCode())
        );
        entity.setRoleId(MenuIndexEnum.GLOBAL.getCode());
        entity.setStatus(BaseConstant.STATUS_1);
        boolean flag = this.save(entity);
        // 清理缓存
        if (flag) {
            redisUtil.del("sys:cache:menuIndex:global");
        }
        return entity;
    }

    /**
     * 获取动态首页路由配置
     *
     * @param userId
     * @return
     */
    @Override
    public String getIndexUrlByUserName(String userId) {
        String indexUrl = null;
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(
                new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId,userId)
        );
        List<String> roles = sysUserRoles.stream().map(n -> n.getRoleId()).collect(Collectors.toList());
        // 对应全部角色的首页配置
        if (CollUtil.isNotEmpty(roles)) {
            List<SysRoleIndex> list = this.list(
                    new LambdaQueryWrapper<SysRoleIndex>()
                            .in(SysRoleIndex::getRoleId, roles)
                            .eq(SysRoleIndex::getStatus, BaseConstant.STATUS_1)
                            .orderByAsc(SysRoleIndex::getPriority)
            );
            if (CollUtil.isNotEmpty(list)) {
                indexUrl = list.get(0).getUrl();
            }
        }
        // 未配置角色，则去查询枚举类中的默认配置
        if (StrUtil.isBlank(indexUrl)) {
            indexUrl = MenuIndexEnum.getMenuIndexByRoles(roles);
        }
        return indexUrl;
    }
}
